package cn.jd.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

@Component
public class LoginFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        //获取请求上下文
        RequestContext requestContext = RequestContext.getCurrentContext();
        // 获取请求头
        HttpServletRequest request = requestContext.getRequest();
        // 获取uri
        String uri = request.getRequestURI();
        // 判断请求是否以login或者register结尾 不存在就false
        if(uri.endsWith("login") || uri.endsWith("register")){
            return false;
        }
        return true;

    }

    @Override
    public Object run() throws ZuulException {
        //获取请求上下文
        RequestContext requestContext = RequestContext.getCurrentContext();
        // 获取请求头
        HttpServletRequest request = requestContext.getRequest();
        // 返回编码集设置
        HttpServletResponse response = requestContext.getResponse();
        response.setContentType("application/json; charset=UTF-8");
        // 获取token
        String token = request.getHeader("token");
        // 判断是否有token有就放行没有就跳转登陆页面
        if(StringUtils.isEmpty(token)){
            try {
                PrintWriter writer = response.getWriter();
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("success", false);
                map.put("message", "请重新登录");
                map.put("resultObject","noLogin");
                // 将map转为json
                String jsonString = JSON.toJSONString(map);
                // 写入
                writer.write(jsonString);
                // 阻止后续filter执行
                RequestContext.getCurrentContext().setSendZuulResponse(false);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
